package com.open.rbac.service.sys.impl;

import java.util.List;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.open.center.common.util.CopyUtils;
import com.open.rbac.model.dto.sys.OrganizationUserRelDto;
import com.open.rbac.model.entity.sys.OrganizationUserRel;
import com.open.rbac.model.vo.sys.OrganizationUserRelVo;
import com.open.rbac.service.sys.IOrganizationUserRelService;
import com.open.rbac.service.sys.repository.OrganizationUserRelRepository;

/**
 * 组织机构与用户关系
 *
 * @author Riche's
 * @since 2025/9/2
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OrganizationUserRelServiceImpl implements IOrganizationUserRelService {

    private final OrganizationUserRelRepository organizationUserRelRepository;

    @Transactional
    @Override
    public void create(List<OrganizationUserRelVo> relVos) {
        List<OrganizationUserRel> rels = relVos.stream().map(relVo -> {
            OrganizationUserRel rel = new OrganizationUserRel();
            rel.setOrganizationId(relVo.getOrganizationId());
            rel.setUserId(relVo.getUserId());
            return rel;
        }).toList();
        organizationUserRelRepository.saveAll(rels);
    }

    @Transactional
    @Override
    public void deleteReallyByUserId(String userId) {
        organizationUserRelRepository.deleteReallyByUserId(userId);
    }

    @Transactional
    @Override
    public void deleteReallyByOrganizationId(String organizationId) {
        organizationUserRelRepository.deleteReallyByOrganizationId(organizationId);
    }


    @Override
    public List<String> listUserIds(List<String> organizationIds) {
        if (CollectionUtils.isEmpty(organizationIds)) {
            return List.of();
        }
        return organizationUserRelRepository.findUserIds(organizationIds);
    }

    @Override
    public List<OrganizationUserRelDto> listByUserIds(List<String> userIds) {
        return CopyUtils.listCopy(organizationUserRelRepository.findByUserIds(userIds), OrganizationUserRelDto.class);
    }
}
